package com.txsj.scan.utils;

import android.text.TextUtils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

/**
 * Created by 刘志博 on 2017/11/28.
 */

public class MD5Util {
    public static String md5(String string) {
        if (TextUtils.isEmpty(string)) {
            return "";
        }
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
            byte[] bytes = md5.digest(string.getBytes());
            String result = "";
            for (byte b : bytes) {
                String temp = Integer.toHexString(b & 0xff);
                if (temp.length() == 1) {
                    temp = "0" + temp;
                }
                result += temp;
            }
            return result;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }


    public static String md5(Map<String,String> params) {
        String string = sortMap(params);

        if (TextUtils.isEmpty(string)) {
            return "";
        }
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
            byte[] bytes = md5.digest(string.getBytes());
            String result = "";
            for (byte b : bytes) {
                String temp = Integer.toHexString(b & 0xff);
                if (temp.length() == 1) {
                    temp = "0" + temp;
                }
                result += temp;
            }
            return result;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }

    public static String sortMap(Map<String,String> params){
        StringBuffer sb=new StringBuffer();
        Map<String,String> map=params;//获取所有的参数
        List<Map.Entry<String,String>> list =new ArrayList<Map.Entry<String,String>>(map.entrySet());//把map转成list
        Collections.sort(list,new Comparator<Map.Entry<String,String>>() {
            public int compare(Map.Entry<String,String> o1,Map.Entry<String, String> o2) {//按字母排序
                return o1.getKey().compareToIgnoreCase(o2.getKey());
            }
        });
        for(int i=0;i<list.size();i++){//拼一下
            String value=list.get(i).getValue();
            if(i==list.size()-1){
                sb.append(list.get(i).getKey()+"="+value);
            }else{
                sb.append(list.get(i).getKey()+"="+value+"&");
            }
        }
        sb.append("&06D36D63A578ACA4FE63C093ABBD2E1E");//拼秘钥

        return sb.toString();
    }
}
